var fs = require('fs');
var util = require('util');

var DefaultRedir = function() {
	var mw = function(req, res, next) {
		debug.debug("	Trying default redirect");
		fs.stat(__root + '/www/' + req.path, function(e, stats) {
			if (e) {
				res.send("Redirect Error: " + util.inspect(e));
			} else if (stats.isDirectory()) {
				fs.readdir(__root + '/www/' + req.path, function(e1, files) {
					if (e1) {
						res.send("Redirect Error: " + util.inspect(e1));
					} else {
						debug.debug(util.inspect(files));
						if (files.indexOf('main.html') > -1) {
							debug.debug("	Found main.html");
							res.redirect(req.path + 'main.html');
						} else if (files.indexOf('index.html') > -1) {
							res.redirect(req.path + 'index.html');
						} else {
							next();
						}
					}
				});
			} else {
				next();
			}
		});
	};

	return mw;
};

module.exports = DefaultRedir;
